<style>
    .div-left{border: 1px solid #ddd;float: left;background-color: #ffffff;height: 900px;}
    .div-right{border: 1px solid #ddd;background-color: #ffffff;height: 900px;margin-left:420px;}
    .search{width: 400px;height: 40px;margin-top: 10px;border: 0px solid #ddd;}
    .left-list{margin-top: 10px;border-top: 1px solid #ddd;}
    .table-list{width: 100%;text-align: center;}
    .table-list>tbody>tr>td{line-height: 45px;}
    .table-user{width: 100%;margin-left: 40px;margin-top: 10px;}
    .table-user>tbody>tr>td,.table-user>tbody>tr>th{line-height: 45px;}
    .user-th{width: 100px;}
    .div-user{border-top: 1px solid #ddd;}
    .dose{border-top: 1px solid #ddd;margin-top: 20px;padding-top: 20px;}
    .td_1{width: 120px;height: 40px;}
    .insulin-value{border-radius:3px;width: 80px;height:34px;border: 1px solid #d2d6de;padding:6px 12px;}
    .dose td{padding-left: 40px;}
    .advice{border-top: 1px solid #ddd;margin-top: 30px;padding-top: 20px;padding-left: 40px;}
    .form-control{display: inline;}
</style>

<body>
<div class="div-left">
    <div>
        <input type="text" class="form-control search" autocomplete="off" id="name" value="<?php if(!empty($_GET['title'])){echo $_GET['title'];}?>" placeholder="请输入名称">
    </div>
    <div class="left-list">
        <table class="table-list">
            <tbody id="table-list-tbody">
                @foreach ($result as $item)
                    <tr class="list-tr" data_id="{{$item->id}}" is_save="{{$item->is_save}}">
                        <td>{{$item->name}}</td>
                        <td style="width: 140px;">
                            @if($item->gender == 1)
                                男
                            @elseif($item->gender == 2)
                                女
                            @else
                                保密
                            @endif
                        </td>
                        <td style="width: 50px;">{{round(getMonthNum($item->birth_at,date('Y-m-d H:i:s',time()),true / 12))}}</td>
                        <td style="width: 100px;">
                            @if($item->is_save == 1)
                                <button style="border:0; height: 20px;line-height: 20px;border-radius: 10px;background-color: red;color:#fff;">有更新</button>
                            @endif
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>
        {{ $result->appends(['user_id' => Request::input("user_id")])->links() }}
    </div>

</div>

<div class="div-right">
    <div style="margin: 14px 0px 14px 30px;">
        <button type="button" class="btn btn-success audit">审 核</button>
        <button type="button" style="margin-left: 40px;" class="btn btn-danger refused">拒绝审核</button>
        <button type="button" style="margin-left: 40px;" class="btn btn-info btn_insulin">历史用药建议</button>
    </div>
    <div class="div-user">
        <table class="table-user">
            <tbody>
                <tr>
                    <th class="user-th" width="30">姓名：</th>
                    <td id="name-value" width="220"></td>
                    <th class="user-th" width="30">性别：</th>
                    <td id="gender" width="220"></td>
                    <th class="user-th" width="30">年龄：</th>
                    <td id="birth_at"></td>
                </tr>
                <tr>
                    <th class="user-th">注册号：</th>
                    <td id="nickname"></td>
                    <th class="user-th">服务期限：</th>
                    <td id="vip"></td>
                    <th class="user-th">状态：</th>
                    <td id="status"></td>
                </tr>
                <tr>
                    <th>更新时间：</th>
                    <td id="save_time"></td>
                    {{--<td colspan='4'>--}}

                    {{--</td>--}}
                </tr>
            </tbody>
        </table>
    </div>
    <div class="dose">
        <label for="txt_statu" style="margin-left: 40px;">剂量建议</label>
        <table id="prescription">
            {{--<tr>--}}
                {{--<td class="td_1" style="width: 200px;">胰岛素 1 & 胰岛素 2</td>--}}
                {{--<td>早餐前</td>--}}
                {{--<td>中餐前</td>--}}
                {{--<td>晚餐前</td>--}}
                {{--<td>睡前</td>--}}
            {{--</tr>--}}
            {{--<tr>--}}
                {{--<td class="td_1"><input type="text" style="width: 150px;" class="form-control insulin-value"></td>--}}
                {{--<td><input type="text" class="form-control insulin-value"> U</td>--}}
                {{--<td><input type="text" class="form-control insulin-value"> U</td>--}}
                {{--<td><input type="text" class="form-control insulin-value"> U</td>--}}
                {{--<td><input type="text" class="form-control insulin-value"> U</td>--}}
            {{--</tr>--}}
        </table>
    </div>
    <div class="advice">
        <label for="txt_parentdepartment">医疗建议</label>
        <textarea rows="9" style="width: 765px;border-radius: 3px;display:block;" id="advice" class="form-control"></textarea>
    </div>
</div>

</body>

<script>
    $(function(){
        //用药记录按钮
        $('.btn_insulin').on('click',function () {
            var user_id = $('.audit').attr("user_id");
            window.location.href = "{{admin_url('/history/advice?user_id=')}}"+user_id;
        });

        //获取药品数据
        var medicinalList = ajaxGetMedicinal();
        var length = $('#table-list-tbody').children().length;
        if ( length > 0 ) {
            var id = $("#table-list-tbody").children("tr").get(0).getAttribute('data_id');
            var is_save = $("#table-list-tbody").children("tr").get(0).getAttribute('is_save');
            $('.audit').attr("user_id", id);
            $('.refused').attr("user_id", id);
            if ( is_save != 1 ) {
                $('.audit').attr("disabled", "disabled");
                $('.refused').attr("disabled", "disabled");
            }else{
                $('.audit').removeAttr("disabled");
                $('.refused').removeAttr("disabled");
            }
            $("#table-list-tbody").children("tr").get(0).setAttribute('style','background-color:#00a65a;color:#fff;');
            ajaxGetUser(id);
            ajaxGetAdvice(id,medicinalList);
        }

        $('.list-tr').click(function () {
            //获取药品数据
            var medicinalList = ajaxGetMedicinal();
            var id = $(this).attr('data_id');
            var is_save = $(this).attr('is_save');
            $('.audit').attr("user_id", id);
            $('.refused').attr("user_id", id);
            if ( is_save != 1 ) {
                $('.audit').attr("disabled", "disabled");
                $('.refused').attr("disabled", "disabled");
            }else{
                $('.audit').removeAttr("disabled");
                $('.refused').removeAttr("disabled");
            }
            $('.list-tr').attr('style','background-color:ffffff;color:#333;');
            $(this).attr('style','background-color:#00a65a;color:#fff;');
            ajaxGetUser(id);
            ajaxGetAdvice(id,medicinalList);
        });

        function monDiff(startTime,endTime){
            startTime = startTime.split('-');
            startTime = parseInt(startTime[0]) * 12 + parseInt(startTime[1]);
            endTime = endTime.split('-');
            endTime = parseInt(endTime[0]) * 12 + parseInt(endTime[1]);
            var month = (Math.abs(startTime - endTime)) / 12;
            return Math.round(month);
        }

        function ajaxGetUser(id) {
            var index = layer.load();
            $.ajax({
                url:"{{admin_url('user/info')}}",
                type: "post",
                data:{"user_id":id},
                success:function (res) {
                    layer.close(index);
                    if(res.code!=0) {
                        layer.msg('操作失败');
                    }
                    var myDate = new Date();
                    var newData = myDate.getFullYear() + '-' + myDate.getMonth();
                    $('#name-value').html(res.data.name);
                    if ( res.data.gender == 1 ) {
                        var gender = '男';
                    } else if( res.data.gender == 2 ) {
                        var gender = '女';
                    }else{
                        var gender = '保密';
                    }
                    $('#gender').html(gender);
                    var html =  res.data.birth_at ? monDiff(res.data.birth_at,newData) : '';
                    $('#birth_at').html(html);
                    $('#nickname').html(res.data.nickname);
                    var html  = res.data.vip_start_at && res.data.vip_end_at ? res.data.vip_start_at.split(' ')[0] + '~' + res.data.vip_end_at.split(' ')[0] : '';
                    $('#vip').html(html);
                    var html = res.data.status == 1 ? '有效' : '无效';
                    $('#status').html(html);
                    $('#save_time').html(res.data.save_time)
                }
            })
        }

        //获取剂量建议,医疗建议
        function ajaxGetAdvice(id,medicinalList) {
            $.ajax({
                url:"{{admin_url('doctor/advice')}}",
                type: "post",
                data:{"user_id":id},
                success:function (res) {
                    console.log(res);
                    if(res.code!=0) {
                        layer.msg('剂量建议获取失败');return;
                    }
                    var group_id = res.data.group_id ? res.data.group_id : 0;
                    $('.audit').attr("group_id", group_id);
                    $('.refused').attr("group_id", group_id);
                    //医疗建议
                    $('#advice').val(res.data.advice);
                    //剂量建议
                    var prescription = res.data.prescription;
                    var prescription_key = res.data.prescription_key;
                    var html ='';
                    html += '<tr>';
                    html +=     '<td class="td_1" style="width: 200px;">胰岛素 1 & 胰岛素 2</td>';
                    html +=     '<td>早餐前</td>';
                    html +=     '<td>中餐前</td>';
                    html +=     '<td>晚餐前</td>';
                    html +=     '<td>睡前</td>';
                    html += '</tr>';
                    if ( prescription ) {
                        console.log(medicinalList);
                        for (var i=0;i<prescription.length;i++) {
                            var strItem = '';
                            html += '<tr>';
                            // html +=     '<td class="td_1"><input type="text" style="width: 250px;" data_id="'+prescription_key[i].id+'" group_id="'+prescription_key[i].group_id+'" insulin_name_en="'+prescription_key[i].insulin_name_en+'" insulin_preparation="'+prescription_key[i].insulin_preparation+'" insulin_type="'+prescription_key[i].insulin_type+'" id="names_'+ i +'" class="form-control insulin-value" value="'+prescription_key[i].insulin_name_cn+'"></td>';
                            //药品下拉框，药品信息用&区分，选择不同的药需要更新这个标签里面得属性
                            html += '   <td class="td_1">' ;
                            html +=        '<select class="form-control default_insulin" data_id="'+prescription_key[i].id+'" group_id="'+prescription_key[i].group_id+'" style="border-radius: 4px;width:250px;" insulin_name_cn="'+prescription_key[i].insulin_name_cn+'" insulin_name_en="'+prescription_key[i].insulin_name_en+'" insulin_preparation="'+prescription_key[i].insulin_preparation+'" insulin_type="'+prescription_key[i].insulin_type+'" name="institution_id" id="names_'+ i +'">';
                            html +=         '<option selected value="'+prescription_key[i].insulin_name_cn+'&'+prescription_key[i].insulin_name_en+'&'+prescription_key[i].insulin_type+'&'+prescription_key[i].insulin_preparation+'">'+prescription_key[i].insulin_name_cn+'</option>';
                            for(var x=0;x<medicinalList.length;x++) {
                                if ( medicinalList[x].medicinal_cn != prescription_key[i].insulin_name_cn || medicinalList[x].medicinal_en != prescription_key[i].insulin_name_en || medicinalList[x].insulin_type != prescription_key[i].insulin_type || medicinalList[x].insulin_preparation != prescription_key[i].insulin_preparation ) {
                                    html +=         '<option value="'+medicinalList[x].medicinal_cn+'&'+medicinalList[x].medicinal_en+'&'+medicinalList[x].insulin_type+'&'+medicinalList[x].insulin_preparation+'">'+medicinalList[x].medicinal_cn+'</option>';
                                }
                            }
                            html +=        '</select>';
                            html +=    '</td>';

                            for ( var j in prescription[i] ) {
                                html +=     '<td><input type="text" id="'+ i + '_' + j +'" class="form-control insulin-value" value="'+prescription[i][j]+'"> U</td>';
                                strItem += prescription[i][j]+',';
                            }
                            html += '</tr>';
                            $('.audit').attr("meals"+i, strItem);
                        }
                        if ( prescription.length == 1 ) {
                            html += '<tr>';
                            html += '   <td class="td_1">' ;
                            html +=        '<select class="form-control default_insulin" data_id="0" group_id="0" style="border-radius: 4px;width:250px;" name="institution_id" id="names_1">';
                            html +=  '<option value="0"></option>';
                            for(var x=0;x<medicinalList.length;x++) {
                                html +=  '<option value="'+medicinalList[x].medicinal_cn+'&'+medicinalList[x].medicinal_en+'&'+medicinalList[x].insulin_type+'&'+medicinalList[x].insulin_preparation+'">'+medicinalList[x].medicinal_cn+'</option>';
                            }
                            html +=        '</select>';
                            html +=    '</td>';
                            html +=     '<td><input type="text" id="1_1" class="form-control insulin-value"> U</td>';
                            html +=     '<td><input type="text" id="1_2" class="form-control insulin-value"> U</td>';
                            html +=     '<td><input type="text" id="1_3" class="form-control insulin-value"> U</td>';
                            html +=     '<td><input type="text" id="1_4" class="form-control insulin-value"> U</td>';
                            html += '</tr>';
                        }
                    }else{
                        for (var i=0;i<=0;i++){
                            html += '<tr>';
                            html += '   <td class="td_1">' ;
                            html +=        '<select class="form-control default_insulin" style="border-radius: 4px;width:250px;" name="institution_id" id="institution_id">';
                            html +=  '<option value="0"></option>';
                            for(var x=0;x<medicinalList.length;x++) {
                                html +=  '<option value="'+medicinalList[x].medicinal_cn+'&'+medicinalList[x].medicinal_en+'&'+medicinalList[x].insulin_type+'&'+medicinalList[x].insulin_preparation+'">'+medicinalList[x].medicinal_cn+'</option>';
                            }
                            html +=        '</select>';
                            html +=    '</td>';
                            html +=     '<td><input type="text" class="form-control insulin-value"> U</td>';
                            html +=     '<td><input type="text" class="form-control insulin-value"> U</td>';
                            html +=     '<td><input type="text" class="form-control insulin-value"> U</td>';
                            html +=     '<td><input type="text" class="form-control insulin-value"> U</td>';
                            html += '</tr>';
                        }
                    }
                    $('#prescription').html(html);
                }
            });
        }

        //审核
        $('.audit').click(function () {
            var group_id = $(this).attr('group_id');
            var user_id = $(this).attr('user_id');
            if ( group_id == 0 || !user_id ) {
                layer.msg('该数据未更新');return;
            }
            var advice = $('#advice').val();
            layer.confirm('你确定要同意吗?', {icon: 3, title:'提示'}, function(index){
                if ( index ) {
                    getPrescriptio(advice,user_id,group_id);
                }
                layer.close(index);
            });
            // getPrescriptio(advice);
        });

        //获取剂量数据
        function getPrescriptio(advice,user_id,group_id) {
            if ( !advice ) {
                layer.msg('医疗建议不能为空');return;
            }
            //判断两个药品是否一样
            if ( document.getElementById("names_0") && document.getElementById("names_1") ) {
                var insulin_name_en_0 = $('#names_0').attr('insulin_name_en');
                var insulin_name_cn_0 = $('#names_0').attr('insulin_name_cn');
                var insulin_preparation_0 = $('#names_0').attr('insulin_preparation');
                var insulin_type_0 = $('#names_0').attr('insulin_type');
                var insulin_name_en_1 = $('#names_1').attr('insulin_name_en');
                var insulin_name_cn_1 = $('#names_1').attr('insulin_name_cn');
                var insulin_preparation_1 = $('#names_1').attr('insulin_preparation');
                var insulin_type_1 = $('#names_1').attr('insulin_type');
                if ( insulin_name_en_0 == insulin_name_en_1 && insulin_name_cn_0 == insulin_name_cn_1 && insulin_preparation_0 == insulin_preparation_1 && insulin_type_0 == insulin_type_1 ) {
                    layer.msg('胰岛素1 & 胰岛素2不能一样');return;
                }
            }
            var index = layer.load();
            var prescription_obj = {};
            if ( document.getElementById("names_0") ) {
                 var item_obj = {
                    'insulin_name_en'   : $('#names_0').attr('insulin_name_en'),
                    'insulin_name_cn'   : $('#names_0').attr('insulin_name_cn'),
                    'insulin_preparation'   : $('#names_0').attr('insulin_preparation'),
                    'insulin_type'   : $('#names_0').attr('insulin_type'),
                    'id'   : $('#names_0').attr('data_id'),
                    'group_id'   : $('#names_0').attr('group_id'),
                    'meals' : [
                        {
                            'meals' : 1,
                            'final_units' : $('#0_1').val(),
                        },
                        {
                            'meals' : 2,
                            'final_units' : $('#0_2').val(),
                        },
                        {
                            'meals' : 3,
                            'final_units' : $('#0_3').val(),
                        },
                        {
                            'meals' : 4,
                            'final_units' : $('#0_4').val(),
                        },
                    ]
                };
                prescription_obj[0] = item_obj;
            }
            if ( document.getElementById("names_1") && $('#names_1').attr('insulin_name_en') ) {
                var item_obj = {
                    'insulin_name_en'   : $('#names_1').attr('insulin_name_en'),
                    'insulin_name_cn'   : $('#names_1').attr('insulin_name_cn'),
                    'insulin_preparation'   : $('#names_1').attr('insulin_preparation'),
                    'insulin_type'   : $('#names_1').attr('insulin_type'),
                    'id'   : $('#names_1').attr('data_id'),
                    'group_id'   : $('#names_1').attr('group_id'),
                    'meals' : [
                        {
                            'meals' : 1,
                            'final_units' : $('#1_1').val(),
                        },
                        {
                            'meals' : 2,
                            'final_units' : $('#1_2').val(),
                        },
                        {
                            'meals' : 3,
                            'final_units' : $('#1_3').val(),
                        },
                        {
                            'meals' : 4,
                            'final_units' : $('#1_4').val(),
                        },
                    ]
                };
                prescription_obj[1] = item_obj;
            }
            console.log(prescription_obj);
            $.ajax({
                url:"{{admin_url('prescription/audit')}}",
                type: "post",
                data:{"prescription_obj":prescription_obj,"advice":advice,"user_id":user_id,"group_id":group_id},
                success:function (res) {
                    layer.close(index);
                    if(res.code!=0) {
                        layer.msg('数据异常');return;
                    }
                    window.location.reload();
                }
            });
        }

        /**
         * 获取药品
         */
        function ajaxGetMedicinal() {
            $.ajax({
                url:"{{admin_url('api/medicinal/list')}}",
                type: "post",
                async:false,
                data:{},
                success:function (res) {
                    console.log(res);
                    if(res.code!=0) {
                        layer.msg('数据异常');return;
                    }
                    window.medicinalLists = res.data;
                }
            });
            return window.medicinalLists;
        }


        //药品下拉框切换事件，更改属性值
        $(document).change('#names_0',function () {
            var value = $('#names_0').val();
            var valueArr = value.split('&');
            $('#names_0').attr('insulin_name_cn',valueArr[0]);
            $('#names_0').attr('insulin_name_en',valueArr[1]);
            $('#names_0').attr('insulin_type',valueArr[2]);
            $('#names_0').attr('insulin_preparation',valueArr[3]);
        });
        $(document).change('#names_1',function () {
            var value = $('#names_1').val();
            var valueArr = value.split('&');
            $('#names_1').attr('insulin_name_cn',valueArr[0]);
            $('#names_1').attr('insulin_name_en',valueArr[1]);
            $('#names_1').attr('insulin_type',valueArr[2]);
            $('#names_1').attr('insulin_preparation',valueArr[3]);
        });

        //拒绝审核
        $('.refused').click(function () {
            var group_id = $('.refused').attr('group_id');
            if ( group_id == 0 || !group_id ) {
                layer.msg('该数据未更新');return;
            }
            layer.confirm('你确定要拒绝吗?', {icon: 3, title:'提示'}, function(index){
                if ( index ) {
                    auditRefused(group_id);
                }
                layer.close(index);
            });
        });
        
        function auditRefused(group_id) {
            $.ajax({
                url:"{{admin_url('api/audit/refused')}}",
                type: "post",
                async:false,
                data:{"group_id":group_id},
                success:function (res) {
                    console.log(res);
                    if(res.code!=0) {
                        layer.msg('数据异常');return;
                    }
                    window.location.reload();
                }
            });
        }
    });
</script>